package com.umanji.building;

import java.io.FileNotFoundException;

import java.io.IOException;
import java.util.ArrayList;

import java.util.Collections;



import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import javax.persistence.NoResultException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.util.WebUtils;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.umanji.building.domain.BuildingInfos;
import com.umanji.building.domain.PublicOfficialBuildings;

import com.umanji.building.domain.Buildings;
import com.umanji.building.service.BuildingService;
//import com.umanji.postgis.domain.PostGISBuilding;
import com.umanji.postgis.domain.Tbbi001;

import com.umanji.postgis.service.PostgisService;
import com.umanji.user.UserController;

/**
 * Handles requests for the application welcome page.
 */
@Controller
@RequestMapping(value="/building")
public class BuildingController {

	private Logger logger = org.slf4j.LoggerFactory.getLogger(BuildingController.class);

	private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
	
	@Autowired
	public BuildingController(Validator validator) {
		this.validator = validator;
	}

    @Autowired
    private BuildingService buildingService;
    
    @Autowired
    private PostgisService postgisService;

    @RequestMapping(value = "/info/{buildingNo}", method = RequestMethod.GET)
    public @ResponseBody String getBuildingInformation(@PathVariable String buildingNo, final HttpServletResponse response) {

		Tbbi001 gisBuildingInfo = postgisService.findByBuildingNo(buildingNo);

    	try {
    		Buildings building = buildingService.findByBuildingNo(buildingNo);
		} catch (NoResultException e) {
			Buildings building = new Buildings( );
			building.setBuildingNo(buildingNo);
			building.setTitle(gisBuildingInfo.getBuildingDetailName());
			building.setContent(gisBuildingInfo.getBuildingMemo());

			buildingService.persist(building);
		} 

		Gson gson = new Gson();
		String json = gson.toJson(gisBuildingInfo); 
		logger.info("json data : " + json);
        return json;  
    }  

    @RequestMapping(value = "/pob/{buildingNo}", method = RequestMethod.GET)
	public @ResponseBody String lookup(@PathVariable String buildingNo, final HttpServletResponse response) {

    	try {
    		PublicOfficialBuildings publicOfficialBuilding = buildingService.findByPobNo(buildingNo);
    		return "true";
		} catch (NoResultException e) {
			return "true";
		} 
	}

    
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public ModelMap buildingtInformation(ModelMap mm) {
		logger.info("show building information form!");

		Buildings ab = buildingService.find( new Long(1) );

		Tbbi001 b = postgisService.findByBuildingNo("1114013600100110067018019");
		logger.info("value building : " + b.getBuildingName());
		logger.info("value building : " + b.getBuildingNo());

		Buildings building = new Buildings( );
		mm.addObject("umj_building", building);
		
        return mm;

	}
    
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public ModelMap create(ModelMap model) {
		logger.info("register category form!");

		Buildings building = new Buildings( );
        model.addObject("umj_building", building);
        return model;

	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@ModelAttribute("umj_form_building") Buildings umanji_building, BindingResult result) {
		logger.info("register user!");

        for (ConstraintViolation<Buildings> constraint : validator.validate(umanji_building)) {
            result.rejectValue(constraint.getPropertyPath().toString(), "", constraint.getMessage());
        }
        if (result.hasErrors())
        	return "/umj/building/create";

        return "redirect:/umj/building/create";
	}

	@RequestMapping(value = "/update/{buildingNo}", method = RequestMethod.GET)
	public ModelMap buildingUpdate(@PathVariable String buildingNo) {
		logger.info("register building infos form!");

		Tbbi001 gisBuildingInfo = postgisService.findByBuildingNo(buildingNo);

    	try {
    		Buildings building = buildingService.findByBuildingNo(buildingNo);
		} catch (NoResultException e) {
			Buildings building = new Buildings( );
			building.setBuildingNo(buildingNo);
			building.setTitle(gisBuildingInfo.getBuildingDetailName());
			building.setContent(gisBuildingInfo.getBuildingMemo());

			buildingService.persist(building);
		} 
		
		ModelMap model = new ModelMap("gisBuildingInfo", gisBuildingInfo);
		BuildingInfos buildingInfos = new BuildingInfos( );
		model.addObject("umj_building_infos", buildingInfos);

		return model;
	}

	@RequestMapping(value = "/update/{buildingNo}", method = RequestMethod.POST)
	public String buildingUpdate( @PathVariable String buildingNo, 
									@RequestParam(value = "name") String[] name,
									@RequestParam(value = "description") String[] description,
									@RequestParam(value = "buildingImageFile") CommonsMultipartFile buildingImageFile,
									HttpServletRequest request) {
		// @ModelAttribute("umj_form_building_infos") BuildingInfos umanji_building_infos,
		logger.info("register building infos!");

    	try {
    		Buildings building = buildingService.findByBuildingNo(buildingNo);
    		
			String rootPath = WebUtils.getRealPath(request.getSession().getServletContext(), "upload");
			building.setImgFile( building.getSavedFileName(rootPath, buildingImageFile, "building") );

    		for (int idx = 0; idx < name.length; idx++) {
        		BuildingInfos buildingInfos = new BuildingInfos(name[idx], description[idx]);
        		buildingInfos.setBuilding(building);
        		Set buildingInfoSet = new HashSet();
    			buildingInfoSet.add(buildingInfos);

    			building.setBuildingInfos(buildingInfoSet);
    			buildingService.merge(building);
    		}
		} catch (NoResultException e) {

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		logger.info("info desc :::::::::::::" + description.toString());
	    for (String s: name)
	    {
	      System.out.println(s);
	    }

		logger.info("info name :::::::::::::" + name.toString());
	    for (String s: description)
	    {
	      System.out.println(s);
	    }

		return "redirect:/umj/building/showInfo/"+buildingNo;
		
	}

	@RequestMapping(value = "/showInfo/{buildingNo}", method = RequestMethod.GET)
	public ModelMap buildingtInformationNo(ModelMap mm, @PathVariable String buildingNo) {
		logger.info("show building information form!");
		Tbbi001 gisBuildingInfo = postgisService.findByBuildingNo(buildingNo);
		Buildings b = buildingService.findByBuildingNo(buildingNo);
		Long id = b.getId();		
		List li = buildingService.findByBuildingId(id);
		
		logger.info("value building img  : " + b.getImgFile());
		logger.info("value building no : " + b.getBuildingNo());

		mm.addObject("umj_building", b);
		mm.addObject("list", li);
		mm.addObject("gisBuildingInfo", gisBuildingInfo);
        return mm;

	}

}
